import React, {useEffect, useState, useRef} from 'react'
import {Button, Space, message, Popconfirm, Tag} from 'antd'
import {PlusOutlined, ArrowDownOutlined} from '@ant-design/icons'

import type {ColumnsType} from 'antd/es/table'
import {connect, history} from 'umi'

import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import Permissions from '@/components/Permissions'
import {
	getTableList,
	deletePayment,
	applypayImport,
	paymentAuditFlow,
} from '@/service/purchase/payment'
import {getDict} from '@/service/common/dict'
import BatchUpload from '@/components/BatchUpload'
import {
	getIsProcessOpen,
	getSupplierBaseExcelList,
} from '@/service/purchase/initiation'
import {modalApi} from '@/utils/modalReq'
import {downloadDocumentUrl} from '@/service/common/download'
import {auditStatus} from '../dict'
import {processRecordSave} from '@/service/common'

const formItemLayout = {
	labelCol: {flex: '140px'},
	wrapperCol: {flex: '1'},
}

interface DataType {
	planNo: string
	principalName: string
	supplierName: string
	resultMsg: string
}

const planDom = (props: any) => {
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	const [dict, setDict] = useState({
		purchase_applypay_paymethod: [],
		audit_status: [],
	})
	const [loading, setLoading] = useState(false)
	const [tableList, setTableList] = useState<any[]>([])
	const [total, setTotal] = useState(0)
	const [searchData, setSearchData] = useState({})
	const [formData, setFormData] = useState<any[]>([])
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [processOpen, setProcessOpen] = useState<number>(0)
	// 初始化-流程是否激活
	const getIsProcessOpenFun = () => {
		getIsProcessOpen({businessType: 5})
			.then((res: any) => {
				if (res?.success) {
					setProcessOpen(() => res?.data)
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	// 获取表格数据
	const onListFun = () => {
		setLoading(true)
		getTableList({...params, ...searchData})
			.then((res: any) => {
				if (res?.data?.records) {
					setTableList(() => res.data.records)
					setTotal(res.data.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}

	useEffect(() => {
		getIsProcessOpenFun()
		getDict(
			{
				dictKeys: ['purchase_applypay_paymethod'],
			},
			(res: any) => {
				setDict(() => res)
			},
		)
	}, [])

	// 获取表格数据
	// 自定义一个初始不更新的hook
	const useUpdateEffect = (fn: Function, inputs: any[]) => {
		const didMountRef = useRef(false)
		useEffect(() => {
			if (didMountRef.current) fn()
			else didMountRef.current = true
		}, inputs)
	}

	// 使用自定义hook
	useUpdateEffect(onListFun, [params])

	// 删除事件
	const onDeleteFun = (ids: string) => {
		deletePayment({ids})
			.then((res) => {
				if (res.success) {
					message.success(res.msg)
					onListFun()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	// 流程作废
	const onAuditFlowFun = (record: {id: string; instanceId: string}) => {
		paymentAuditFlow({
			businessId: record?.id,
			instanceId: record?.instanceId,
			pass: '3',
			message: JSON.stringify({
				userName: props?.user?.userName,
				message: '已作废',
			}),
		})
			.then((res: {msg: string; success: boolean}) => {
				if (res?.success) {
					message.success(res.msg)
					processRecordSave({
						bizType: 5,
						bizNo: record?.id,
						processId: record?.instanceId,
					})
					onListFun()
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}

	// 列表
	const columns: ColumnsType<planAPI.columns> = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text, record, index) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '付款申请单编号',
			dataIndex: 'applypayNo',
			align: 'center',
			width: 200,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '审核状态',
			dataIndex: 'auditStatus',
			align: 'center',
			width: 140,
			render: (text: number, record: any) => (
				<>
					{auditStatus?.map((item: {key: number; label: string}) => {
						if (item?.key === Number(text)) {
							return (
								<Tag color="processing" key={record?.id}>
									{item?.label}
								</Tag>
							)
						}
						return null
					})}
				</>
			),
		},
		{
			title: '关联采购计划申请单编号',
			dataIndex: 'planNo',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '合同编号',
			dataIndex: 'contractNo',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '合同名称',
			dataIndex: 'contractName',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '付款类型',
			dataIndex: 'payMethodname',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '付款金额',
			dataIndex: 'amount',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '剩余未核销金额',
			dataIndex: 'unwrittenAmount',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '收款单位',
			dataIndex: 'supplierName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '申请日期',
			dataIndex: 'applyTime',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text) => (
				<span>
					{' '}
					{processOpen === 1
						? moment(text).format('YYYY-MM-DD HH:mm:ss')
						: moment(text).format('YYYY-MM-DD')}
				</span>
			),
		},
		{
			title: '申请人',
			dataIndex: 'applicantName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (text, record) => (
				<div>
					<Permissions permissionID="amc_assetCenter_purchase_payment_view">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/purchase/payment/view',
									query: {
										id: record.id,
									},
								})
							}}>
							详情
						</Button>
					</Permissions>
					{record?.isAudit === 1 && record?.auditStatus !== '4' ? (
						<Permissions permissionID="amc_assetCenter_purchase_payment_process">
							<Button
								type="link"
								size="small"
								onClick={() => {
									history.push({
										pathname: '/purchase/payment/process',
										query: {
											id: record.id,
										},
									})
								}}>
								审核
							</Button>
						</Permissions>
					) : null}
					{String(record?.createUser) ===
					String(props?.user?.userId) ? (
						<>
							{record?.auditStatus === '3' ? (
								<Permissions permissionID="amc_assetCenter_purchase_payment_cancel">
									<Popconfirm
										placement="topLeft"
										title="你确定要作废这条数据吗？"
										onConfirm={() => onAuditFlowFun(record)}
										okText="确定"
										cancelText="取消">
										<Button type="link" size="small">
											作废
										</Button>
									</Popconfirm>
								</Permissions>
							) : null}
							{record?.auditStatus === '9' ? (
								<>
									<Permissions permissionID="amc_assetCenter_purchase_payment_edit">
										<Button
											type="link"
											size="small"
											onClick={() => {
												history.push({
													pathname:
														'/purchase/payment/edit',
													query: {
														id: record.id,
													},
												})
											}}>
											编辑
										</Button>
									</Permissions>
								</>
							) : null}
							{record?.auditStatus === '4' ? (
								<>
									<Permissions permissionID="amc_assetCenter_purchase_payment_reissue">
										<Button
											type="link"
											size="small"
											onClick={() => {
												history.push({
													pathname:
														'/purchase/payment/edit',
													query: {
														id: record.id,
													},
												})
											}}>
											再次发起
										</Button>
									</Permissions>
								</>
							) : null}
							{record?.auditStatus === '9' ||
							record?.auditStatus === '4' ? (
								<Permissions permissionID="amc_assetCenter_purchase_payment_delete">
									<Popconfirm
										placement="topLeft"
										title="你确定要删除这条数据吗？"
										onConfirm={() => onDeleteFun(record.id)}
										okText="确定"
										cancelText="取消">
										<Button type="link" size="small">
											删除
										</Button>
									</Popconfirm>
								</Permissions>
							) : null}
						</>
					) : null}
				</div>
			),
		},
	]
	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [searchData])

	// 搜索
	const onFinish = (values: any) => {
		setSearchData(values)
	}
	// 重置
	const onReset = () => {
		setSearchData({})
	}
	// 导出事件
	const onExportClick = () => {
		downloadDocumentUrl({
			resourceId: '144',
			queryDesc: '付款申请导出,resourceId:144',
			queryParam: searchData,
		})
	}

	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'input',
						label: '付款申请单号',
						name: 'applypayNo',
						key: 'applypayNo',
					},
					{
						type: 'input',
						label: '采购计划申请单编号',
						name: 'planNo',
						key: 'planNo',
					},
					{
						type: 'input',
						label: '收款单位',
						name: 'ledgerName',
						key: 'ledgerName',
					},
				],
			},
			{
				type: 'group',
				key: 'group2',
				groupItems: [
					{
						type: 'input',
						label: '合同编号',
						name: 'contractNo',
						key: 'contractNo',
					},
					{
						type: 'select',
						key: 'payMethod',
						name: 'payMethod',
						label: '付款类型',
						keys: 'dictKey',
						title: 'dictValue',
						items: [...dict.purchase_applypay_paymethod],
					},
					{
						type: 'select',
						key: 'auditStatus',
						name: 'auditStatus',
						label: '审核状态',
						keys: 'key',
						title: 'label',
						items: [...auditStatus],
					},
				],
			},
		]
		setFormData(formItems)
	}, [dict])

	const errorColumns: ColumnsType<DataType> = [
		{
			title: '采购计划申请单号',
			dataIndex: 'planNo',
			align: 'center',
		},
		{
			title: '付款类型',
			dataIndex: 'payMethodname',
			align: 'center',
		},
		{
			title: '供应商名称',
			dataIndex: 'supplierName',
			align: 'center',
		},
		{
			title: '失败原因',
			dataIndex: 'resultMsg',
			align: 'center',
		},
	]
	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Permissions permissionID="amc_assetCenter_purchase_payment_add">
						<Button
							icon={<PlusOutlined />}
							type="primary"
							ghost
							size="small"
							onClick={() => {
								history.push('/purchase/payment/add')
							}}>
							新增
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_purchase_payment_import">
						<Button
							icon={<ArrowDownOutlined />}
							ghost
							size="small"
							className="btn_import"
							onClick={() => setIsUploadModalOpen(true)}>
							导入
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_purchase_payment_export">
						<Button
							icon={<ArrowDownOutlined />}
							ghost
							size="small"
							className="btn_warning"
							onClick={onExportClick}>
							导出
						</Button>
					</Permissions>
				</Space>
			</div>
			<div className="table">
				<CustomTable
					params={params}
					columns={columns}
					pagination
					total={total}
					scroll={{y: 480}}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={tableList}
				/>
			</div>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={applypayImport}
				onTableList={getSupplierBaseExcelList}
				getListData={onListFun}
				fileNmae="file"
				uploadFileUrl={`${modalApi.purchase}/shopec-purchase-applypay/applypay/import/view`}
				columns={errorColumns}
				sourceId={14}
				templateType="付款申请"
			/>
		</div>
	)
}
export default connect(({user}: any) => ({
	user,
}))(planDom)
